<!--
 * @Author: your name
 * @Date: 2021-12-29 16:01:42
 * @LastEditTime: 2022-01-10 15:17:55
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \custom-app\src\modules\AppCenter\AppModulesDesigner\component\FormGenerator\component\ocr\ocrUpload.vue
-->
<template>
  <fks-upload
    v-bind="$attrs"
    class="upload"
    action=""
    accept=".jpg,.png,.jpeg"
    :before-upload="beforeUpload"
    :limit="1"
    :file-list="fileList"
    :show-file-list="false"
    :http-request="handleUpload"
  >
    <fks-button icon="fks-icon-upload-line" type="small" :loading="loading"
      >上传</fks-button
    >
    <span slot="tip" class="fks-upload__tip"> 只能上传jpg/png/jpeg文件 </span>
  </fks-upload>
</template>

<script>
// import axios from 'axios'
import { getSign } from '@/utils/request/sign'
import request from '@/utils/request'
// const cancelTokenObj = new Map()
export default {
  name: 'ocrUpload',
  data() {
    return {
      loading: false,
      fileList: []
    }
  },
  methods: {
    beforeUpload(file) {
      //校验文件格式
      const reg = /(png|jpg|jpeg|image)/
      let isImg = reg.test(file.type)
      if (!isImg || file.size === 0) {
        this.$message({
          message: '不支持的文件格式',
          type: 'warning'
        })
        return false
      }
    },
    handleUpload(file) {
      let formData = new FormData()
      formData.append('files', file.file)
      // const fileId = file.file.uid
      //生成取消请求的token,方便在handleRemove取消上传时结束请求
      // const CancelToken = axios.CancelToken
      // const source = CancelToken.source()
      // cancelTokenObj.set(fileId, source)
      //给FormCenter/index.vue派发事件，表示有文件上传中。
      this.loading = true
      request({
        url: '/sys-storage/ocr',
        method: 'post',
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        params: getSign(),
        data: formData,
        timeout: 0
        // cancelToken: source.token,
        // onUploadProgress: (progressEvent) => {
        //   let percent = ((progressEvent.loaded / progressEvent.total) * 100) | 0
        //   //调用onProgress方法来显示进度条，需要传递个对象 percent为进度值
        //   file.onProgress({ percent: percent })
        // }
      })
        .then((res) => {
          this.loading = false
          this.fileList = []
          if (res.status) {
            this.$emit('change', res)
          }

          // this.console.log(res)
          //上传成功后，派发上传成功事件
          // file.onSuccess(res.data)
        })
        .catch((err) => {
          this.loading = false
          console.log(err)
          // file.onError(err)
        })
    }
  }
}
</script>

<style></style>
